/**
 * 
 */
package edu.arizona.eller.mis.hippo.facade;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import edu.arizona.eller.mis.hippo.exception.SimpleException;

/**
 * @author Blaine Boule
 * October 24, 2011
 *
 */
public class CraigsListFacade {
	
	private static final String _URL = "http://tucson.craigslist.org/search/sss/?";
	private static final String _AREA_PARAM = "areaID=57";
	private static final String _SUBAREA_PARAM = "&subAreaID=";
	private static final String _QUERY_PARAM = "&query=";
	private static final String _FORMAT_PARAM = "&format=rss";
	private static final String _SEARCH_TYPE_PARAM = "&srchType=A";
	
	private static final String _TITLE_SEARCH = "T";

	public Document fullSearch(String queryTerm) throws SimpleException{
		if(queryTerm != null && !queryTerm.isEmpty()){
			String conncetionUrl = buildUrl(null, null, queryTerm, null);
			String result = connect(conncetionUrl);
			return convertToDOM(result);
		}else{
			throw new SimpleException("Search requires a search term, null or empty terms are not permitted");
		}
		
	}
	
	public Document titleSearch(String queryTerm) throws SimpleException{
		if(queryTerm != null && !queryTerm.isEmpty()){
			String conncetionUrl = buildUrl(null, null, queryTerm, _TITLE_SEARCH);
			String result = connect(conncetionUrl);
			return convertToDOM(result);
		}else{
			throw new SimpleException("Search requires a search term, null or empty terms are not permitted");
		}
		
	}	
	
	private String connect(String urlString){
		URL url;
		StringBuffer result = new StringBuffer();
		InputStreamReader is = null;
		BufferedReader in = null;
		try {
			url = new URL(urlString);
			is = new InputStreamReader(url.openStream());
		    in = new BufferedReader(is);
	        String inputLine;

	        while ((inputLine = in.readLine()) != null)
	        	result.append(inputLine);
		   
		    
			if(result.toString().equalsIgnoreCase("")){
				return null;
			}
			return result.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(is != null){
					is.close();
				}
				if(in != null){
					in.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
		
	}
	
	private String buildUrl(String area, String subArea, String query, String type){
		StringBuffer urlString = new StringBuffer(_URL);
		if(area != null && !area.isEmpty()){
			urlString.append(_AREA_PARAM.substring(0, _AREA_PARAM.indexOf("=")));
		}else{
			urlString.append(_AREA_PARAM);
		}
		
		if(subArea != null && !subArea.isEmpty()){
			urlString.append(_SUBAREA_PARAM.substring(0, _SUBAREA_PARAM.indexOf("=")));
		}else{
			urlString.append(_SUBAREA_PARAM);
		}
		
		if(query != null && !query.isEmpty()){
			urlString.append(_QUERY_PARAM);
			urlString.append(query);
		}else{
			urlString.append(_QUERY_PARAM);
		}
		
		if(type != null && !type.isEmpty()){
			urlString.append(_SEARCH_TYPE_PARAM.substring(0, _SEARCH_TYPE_PARAM.indexOf("=")));
		}else{
			urlString.append(_SEARCH_TYPE_PARAM);
		}
		urlString.append(_FORMAT_PARAM);
		
		return urlString.toString();
	}
	
	private Document convertToDOM(String xml) throws SimpleException{
		Document doc = null;
		InputStream is = null;
		if(xml != null){		    
			try {				
				is = new ByteArrayInputStream(xml.getBytes());
			    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				doc = builder.parse(is);
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
				throw new SimpleException("ParseException occured during document creation");
			} catch (SAXException e) {
				e.printStackTrace();
				throw new SimpleException("SAXException occured during document creation");
			} catch (IOException e) {
				e.printStackTrace();
				throw new SimpleException("IOException occured during document creation");
			}finally{
				if(is != null){
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();//We tried
					}
				}
			}
		}
		return doc;
	}
}
